package com.rzgeo.wcgallay.comp;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.rzgeo.wcgallay.util.WcmUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;

/**
 * Created by zhanghang on 2017/12/26.
 */
public class WcmValueTxv extends android.support.v7.widget.AppCompatTextView {
    private int _iUnit=-1;
    private Unit[] _units;
    private double _value;
    private DecimalFormat _dataFormart;
    private ArrayList<String> _unitsTitles;
    private WcmUtil.Dialog.OnList _onUnitSelect=new WcmUtil.Dialog.OnList() {
        @Override
        public void onConfirm(int select) {
            if(select!=_iUnit){
                _iUnit=select;
                updateValue();
            }
        }

        @Override
        public void onCancel() {

        }

        @Override
        public void onNeutral() {

        }
    };


    public WcmValueTxv(Context context) {
        super(context);
    }

    public WcmValueTxv(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public WcmValueTxv(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        _dataFormart=new   java.text.DecimalFormat("0.00");
        this.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                WcmUtil.Dialog.List(
                        getContext(),
                        "选择一个统计单位:",
                        _unitsTitles,
                        null,
                        _iUnit,
                        _onUnitSelect

                );
            }
        });
    }

    public void setValue(double value,Unit[]units,int iDefautUnit,boolean rewrite){
        if(rewrite||(_iUnit<0))
            _iUnit=iDefautUnit;

        _units=units;
        _value=value;

        _unitsTitles=new ArrayList<>();
        for(Unit u:_units){
            _unitsTitles.add(u.name);
        }

        updateValue();
    }

    private void updateValue() {
        Unit unil = _units[_iUnit];
        setText(
                _dataFormart.format(
                        _value/unil.scale)+unil.name);
    }

    public static class Unit{
        public final String name;
        public final double scale;

        public Unit(String name, double scale) {
            this.name = name;
            this.scale = scale;
        }
    }
}
